package com.lst.selfaiagent.app;

import cn.hutool.extra.mail.MailUtil;
import com.lst.selfaiagent.SelfAiAgentApplication;
import com.lst.selfaiagent.advisors.MyCustomAdvisor;
import com.lst.selfaiagent.advisors.MyLoggerAdvisor;
import com.lst.selfaiagent.advisors.ReReadingAdvisor;
import com.lst.selfaiagent.advisors.VerificationAdvisor;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.messages.Message;

import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.model.Media;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;


@Component
public class LoveApp {

    @Value("classpath:/prompts/system-message.st")
    private Resource systemResource;

    private static final Logger log = LoggerFactory.getLogger(LoveApp.class);
    private ChatClient chatClient;

    private ChatClient jokeChatClient;
    @Autowired
    private ChatModel ollamaChatModel;
    @Autowired
    private VectorStore loveAppVectorStore;

    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

    // 移除构造函数，使用@PostConstruct初始化
    @PostConstruct
    public void init() {
        // 创建新的聊天内存实现
        ChatMemory chatMemory = MessageWindowChatMemory.builder()
                .chatMemoryRepository(new InMemoryChatMemoryRepository())
                .maxMessages(20) // 设置最大消息数
                .build();
        
        chatClient = ChatClient.builder(ollamaChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        // 聊天记忆
                        MessageChatMemoryAdvisor.builder(chatMemory)
                                .conversationId("default-conversation")
                                .build()
                        ,new MyLoggerAdvisor()
                        ,new ReReadingAdvisor()
                        ,new VerificationAdvisor()
                )
                .build();

        // 新增笑话专家客户端
        jokeChatClient = ChatClient.builder(ollamaChatModel)
                .defaultSystem("你是一个专业的幽默大师和笑话专家，擅长讲各种类型的笑话。请根据用户的要求讲一个合适的笑话。")
                .defaultAdvisors(
                        MessageChatMemoryAdvisor.builder(chatMemory)
                                .conversationId("joke-conversation")
                                .build(),
                        new MyLoggerAdvisor(),
                        new ReReadingAdvisor())
                .build();
    }

    public  String doChat(String message, String chatId){
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String text = chatResponse.getResult().getOutput().getText();
////        log.info("ChatResponse: {}", chatResponse);
        log.info("text: {}", text);
        return text;
    }
    public  String doJokeChat(String message, String chatId){
        ChatResponse chatResponse = jokeChatClient
                .prompt(jokePrompt())
                .user(message)
                .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String text = chatResponse.getResult().getOutput().getText();
////        log.info("ChatResponse: {}", chatResponse);
        log.info("text: {}", text);
        return text;
    }

    // 结构化输出格式
    public record LoveReport(String title, List<String> suggestions) { }

    public LoveReport doChatWithReport(String message, String chatId) {
        LoveReport loveReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);
        log.info("loveReport: {}", loveReport);
        return loveReport;
    }

    public String doChatWithRag(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                // 应用知识库问答
                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    // 解释图片内容 - 增强版
    public String doImageChat(String imgUrl, String chatId) {
        try {
            // 验证URL格式
            if (imgUrl == null || imgUrl.trim().isEmpty()) {
                return "请提供有效的图片链接";
            }

            ChatResponse chatResponse = chatClient
                    .prompt()
                    .system("请解释图片内容")
                    .user(u -> {
                        try {
                            URL url = new URL(imgUrl);

                            // 验证是否为图片URL（简单检查）
                            String lowerUrl = imgUrl.toLowerCase();
                            if (!lowerUrl.endsWith(".jpg") && !lowerUrl.endsWith(".jpeg")
                                    && !lowerUrl.endsWith(".png") && !lowerUrl.endsWith(".gif")
                                    && !lowerUrl.endsWith(".webp")) {
                                log.warn("URL might not be an image: {}", imgUrl);
                            }

                            u.text("我提供了图片链接，请分析这张图片的内容,图片链接是:"+imgUrl);

                        } catch (MalformedURLException e) {
                            log.error("Invalid image URL format: {}", imgUrl, e);
                            u.text("提供的图片链接格式不正确: " + imgUrl);
                        } catch (Exception e) {
                            log.error("Error processing image from URL: {}", imgUrl, e);
                            u.text("无法处理提供的图片链接，请检查链接是否正确且可访问");
                            return ;
                        }
                    })
                    .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                            .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                    .call()
                    .chatResponse();

            String text = chatResponse.getResult().getOutput().getText();
            log.info("Image analysis result: {}", text);
            return text;

        } catch (Exception e) {
            log.error("Error processing image chat request for URL: {}", imgUrl, e);
            return "处理图片时发生错误，请稍后重试";
        }
    }

    // 获取文件扩展名
    private String getFileExtension(String imgUrl) {
        try {
            String lowerUrl = imgUrl.toLowerCase();
            if (lowerUrl.endsWith(".png")) return ".png";
            if (lowerUrl.endsWith(".gif")) return ".gif";
            if (lowerUrl.endsWith(".webp")) return ".webp";
            if (lowerUrl.endsWith(".jpg")) return ".jpg";
            if (lowerUrl.endsWith(".jpeg")) return ".jpeg";
            return ".jpg"; // 默认
        } catch (Exception e) {
            return ".jpg";
        }
    }

    // 辅助方法：根据URL确定MIME类型
    private MimeType determineMimeType(String imgUrl) {
        String lowerUrl = imgUrl.toLowerCase();
        if (lowerUrl.endsWith(".png")) {
            return MimeTypeUtils.IMAGE_PNG;
        } else if (lowerUrl.endsWith(".gif")) {
            return MimeTypeUtils.IMAGE_GIF;
        } else if (lowerUrl.endsWith(".webp")) {
            return MimeType.valueOf("image/webp");
        } else if (lowerUrl.endsWith(".jpg") || lowerUrl.endsWith(".jpeg")) {
            return MimeTypeUtils.IMAGE_JPEG;
        } else {
            // 默认使用JPEG
            return MimeTypeUtils.IMAGE_JPEG;
        }
    }

    // 笑话提示词模板
    public Prompt jokePrompt() {

        PromptTemplate promptTemplate = new PromptTemplate("你要给我将一个关于{key1}和{key2}的笑话");
        Message promptTemplateMessage = promptTemplate.createMessage(Map.of("key1", "暴力", "key2", "色情"));


//        String systemText = "你是一个幽默的笑话生成器，请生成一个笑话，你的名字是{name}";
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate((systemResource));
        Message systemPromptTemplateMessage = systemPromptTemplate.createMessage(Map.of("name", "小王"));
        return new Prompt(promptTemplateMessage, systemPromptTemplateMessage);
    }

    // test提交

}